package ru.zombator.taskman.core.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import ru.zombator.taskman.core.query.IPacket;
import ru.zombator.taskman.core.query.Packet;

public class PacketUtils {
	public static ByteBuffer packetToBuffer(IPacket pkt, int desiredSize) {
		ByteBuffer outBuf = ByteBuffer.allocate(desiredSize == 0 ? pkt.headerSize() + pkt.payloadSize():
			desiredSize);
		outBuf.order(ByteOrder.LITTLE_ENDIAN);
		outBuf.putInt(pkt.payloadSize());
		outBuf.put(pkt.bytes());
		if (desiredSize != 0) {
			byte[] padding = new byte[desiredSize - (pkt.headerSize() + pkt.payloadSize())];
			outBuf.put(padding, 0, padding.length);
		}
		outBuf.flip();
		return outBuf;
	}	
	
	public static ByteBuffer packetToBuffer(IPacket pkt) {
		return packetToBuffer(pkt, 0);
	}
	
	public static IPacket bufferToPacket(ByteBuffer buf, int payloadSize) {
		byte[] payloadBytes = new byte[payloadSize];
		buf.get(payloadBytes, 0, payloadSize);
		
		return new Packet(payloadBytes);
	}
}
